package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IFollowService followService;


    //保存博文


    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = this.save(blog);
        if (!isSuccess) {
            return Result.fail("新增笔记失败");
        }
        //查询笔记作者的所有粉丝
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getFollowUserId, user.getId());
        List<Follow> follows = followService.list(queryWrapper);
        //推送笔记id给所有粉丝
        for(Follow follow:follows){
            //获取粉丝id
            Long userId = follow.getUserId();
            //推送
            String key= "feed:" + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    // 查询博客详情
    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("博客不存在");
        }
        // 查询blog有关的用户
        Long UserId= blog.getUserId();
        User user = userService.getById(UserId);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        //获取当前登录用户
        UserDTO userDTO = UserHolder.getUser();
        if(userDTO==null){
            // 未登录，无需查询
            return ;
        }
        Long UserId = userDTO.getId();
        // 判断当前用户是否已经点赞
        String key= "blog:liked:" + blog.getId();
        Double score= stringRedisTemplate.opsForZSet().score(key, UserId.toString());
        blog.setIsLike(score!=null);  //score不为空，表示已经点赞
    }

    // 给博客点赞

    @Override
    public Result likeBlog(Long id) {
        //获取当前登录用户
        Long UserId = UserHolder.getUser().getId();
        // 判断当前用户是否已经点赞
        String key= "blog:liked:" + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, UserId.toString());
        if (score==null) {
            // 如果未点赞，可以点赞
            // 数据库点赞数+1
            boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
            //保存用户id到redis中的set集合
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, UserId.toString(), System.currentTimeMillis());
            }
        }else{
                boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
                if (isSuccess) {
                    stringRedisTemplate.opsForZSet().remove(key, UserId.toString());
                }
            }
        return Result.ok();
    }


    // 查询点赞列表
    @Override
    public Result queryBlogLikes(Long id) {
        String key= "blog:liked:" + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4); //获取排名前五的点赞用户id
        if (top5==null||top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //将ids转为Long类型
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",", ids);
        List<UserDTO> userDTOList = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id,"+join+")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOList);
    }

    //查询关注的博主的笔记
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 查询收件箱
        String key = "feed:" + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        // 非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        //解析数据
        List<Long> ids=new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os=1;
        for(ZSetOperations.TypedTuple<String> tuple:typedTuples){
            //获取笔记id
            String blogId = tuple.getValue();
            ids.add(Long.valueOf(blogId));
            // 获取分数（时间戳）
            long time = tuple.getScore().longValue();
            if(time==minTime){
                os++;
            }else{
                minTime = time;
                os=1;
            }
        }

        // 查询笔记
        String join = StrUtil.join(",", ids);
        List<Blog> blogList = query().in("id", ids).last("ORDER BY FIELD(id," + join + ")").list();

        //查询笔记作者和点赞数据
        for(Blog blog:blogList){
            Long UserId= blog.getUserId();
            User user = userService.getById(UserId);
            blog.setIcon(user.getIcon());
            blog.setName(user.getNickName());
            isBlogLiked(blog);
        }

        // 返回数据
        ScrollResult result = new ScrollResult();
        result.setList(blogList);
        result.setOffset(os);
        result.setMinTime(minTime);

        return Result.ok(result);
    }
}
